package com.waves.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.waves.core.utils.LoginUtils;
import com.waves.pay.domain.entity.Orders;
import com.waves.pay.domain.dto.AlipayDto;
import com.waves.pay.service.AlipayService;
import com.waves.pay.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {
    public static final String FAST_INSTANT_TRADE_PAY = "FAST_INSTANT_TRADE_PAY";
    // 「沙箱环境」服务器异步通知回调地址
    public static String notify_url = "http://localhost/demand/alipay/alipay_notify_url";
    // 「沙箱环境」页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String return_url = "http://www.baixian.asia";

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private OrderService orderService;

    @Override
    @Transactional
    public String pay(AlipayDto alipayDto) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(notify_url);
        request.setReturnUrl(return_url);
        JSONObject bizContent = new JSONObject();
        // 生成自定义订单号码
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        double money = alipayDto.getReceiveId() == null
                ? alipayDto.getBounty() * alipayDto.getBountyNum() : alipayDto.getBounty();
        String number = "task" + sdf.format(new Date());
        bizContent.put("out_trade_no", number);
        bizContent.put("total_amount", money); // 订单的总金额
        bizContent.put("subject", alipayDto.getSubject());   // 支付的名称
        bizContent.put("product_code", FAST_INSTANT_TRADE_PAY);  // 固定配置
        request.setBizContent(bizContent.toString());
        String form = null;
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("返回的html页面：{}", form);
        assert form != null;
        int endIndex = form.indexOf("</form>") + "</form>".length();
        // 将信息存到订单表中
        Orders order = new Orders().setOutTradeNo(number)
                .setTaskId(alipayDto.getId())
                .setTotalAmount(alipayDto.getBounty())
                .setSubject(alipayDto.getSubject())
                .setReceiveId(alipayDto.getReceiveId());
        orderService.save(order);
        return form.substring(0, endIndex);
    }
}
